package com.simple.mq.core.config;

import com.alibaba.fastjson.JSON;
import com.simple.mq.common.entity.RegisterQueueInfo;
import com.simple.mq.sdk.consumer.SimpleMqConsumer;
import com.simple.mq.core.network.core.QueueManager;
import com.simple.mq.core.network.core.WorkerManager;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-14 20:19
 **/
@Slf4j(topic = "DefaultConsumer")
public class DefaultConsumer implements Runnable {

    public static final String DEFAULT_URL = "ws://localhost:18888/";

    @Override
    public void run() {
        SimpleMqConsumer simpleMqConsumer = new SimpleMqConsumer(URI.create(DEFAULT_URL), "Default Consumer");
        simpleMqConsumer.register("default", true);
        simpleMqConsumer.onMessage((String message) -> {
            log.info("接收新来的队列注册：【{}】", message);
            Map<String, String> names2BindingKeys = new HashMap<>(2);
            try {
                List<RegisterQueueInfo> registerQueueInfos = JSON.parseArray(message, RegisterQueueInfo.class);
                registerQueueInfos.stream()
                        .filter(registerQueueInfo -> Objects.nonNull(registerQueueInfo.getRewrite()) && registerQueueInfo.getRewrite()
                                || !QueueManager.containsQueue(registerQueueInfo.getQueueName()))
                        .forEach(registerQueueInfo -> names2BindingKeys.put(registerQueueInfo.getQueueName(), registerQueueInfo.getBindingKey()));
            } catch (Exception e) {
                log.error("请输出正确的注册信息【{}】", message, e);
            }
            QueueManager.init(names2BindingKeys);
            WorkerManager.init(names2BindingKeys.keySet());
            log.info("目前已存在的队列：【{}】", JSON.toJSONString(QueueManager.getQueueMap().keySet()));
        });
    }
}
